package com.kc.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kc.bean.Article;
import com.kc.bean.Comment;
import com.kc.bean.UserAccount;
import com.kc.mapper.CommentMapper;
import com.kc.service.ICommentService;
import com.kc.service.IUserAccountService;
import com.kc.util.RedisUtil;
import com.kc.util.ResponesBean;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author jobob
 * @since 2019-10-25
 */
@Service
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements ICommentService {

    @Resource
    private CommentMapper commentMapper;

    @Resource
    private IUserAccountService accountService;

    @Resource
    private ResponesBean responesBean;


    /**
     * 文章评论接口
     * @param comment
     * @param token
     * @return
     */
    @Override
    public ResponesBean AddComment(Comment comment, String token) {
        try {
            //先查询出用户的信息检验当前用户。
//            UserAccount userAccount = accountService.getUserAccount(token);
            String id = accountService.getAccount(token);
            comment.setAccountId(id);
            int i = commentMapper.insert(comment);
            if (i==1){
                responesBean.setAll(200,"插入成功。",comment);
                RedisUtil.Addscore(1,comment.getArticleId());
                return responesBean;
            }
        }catch (DataIntegrityViolationException e){
            responesBean.setAll(400,"评论失败请查看是否登录",null);
            return responesBean;
        }
        responesBean.setAll(400,"评论失败请查看是否登录",null);
        return responesBean;
    }

    @Override
    public int updateComment(Comment comment) {
        return commentMapper.update(comment,new UpdateWrapper<>());
    }

    @Override
    public List<Comment> getComment(String ArticleId) {
        return commentMapper.getComment(Wrappers.<Comment>lambdaQuery().eq(Comment::getArticleId,ArticleId));
    }
}
